//
//  PublishImgViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/9/27.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "PublishImgViewController.h"
#import "RentVieitor.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "UIImageView+WebCache.h"
#import "PublishSuccessViewController.h"


@interface PublishImgViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@end

@implementation PublishImgViewController {
    
    UIImageView *editView;
}

- (void)viewWillAppear:(BOOL)animated {
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(-5, 0, 10, 15);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationController.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"发布租房信息";
    self.view.backgroundColor = BackgroundColor;
    self.imgData = [[NSMutableArray alloc]initWithObjects:@"",@"",@"",@"",@"", nil];
    [self creatLeftView];
    [self creatView];
    
    
}

- (void)creatLeftView {
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 120)];
    headView.backgroundColor = [Utils colorConvertFromString:@"#1fae0c"];
    [self.view addSubview:headView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, KWidth-200, 40)];
    label.text = @"发布租房信息";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:17];
    label.textColor = [UIColor whiteColor];
    [headView addSubview:label];
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(15, 20+12, 100,30);
    [leftBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 10, 90)];
    [leftBtn setImage:[UIImage imageNamed:@"箭头左-left"] forState:UIControlStateHighlighted];
    [leftBtn setImage:[UIImage imageNamed:@"箭头左-left"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:leftBtn];
    
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(KWidth-65, 20+10, 50, 20);
    [rightBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:rightBtn];
    
    UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, KWidth, KWidth*102/788)];
    imgview.image = [UIImage imageNamed:@"publishImg"];
    [headView addSubview:imgview];
    
    UILabel *firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 140, KWidth, 20)];
    firstLabel.text = @"第三步  上传照片";
    firstLabel.textAlignment = NSTextAlignmentCenter;
    firstLabel.font = [UIFont systemFontOfSize:17];
    firstLabel.textColor = [Utils colorConvertFromString:@"#101010"];
    [self.view addSubview:firstLabel];
    
    UILabel *secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 170, KWidth, 13)];
    secondLabel.text = @"请选择图片进行上传";
    secondLabel.textAlignment = NSTextAlignmentCenter;
    secondLabel.font = [UIFont systemFontOfSize:13];
    secondLabel.textColor = [Utils colorConvertFromString:@"#666666"];
    [self.view addSubview:secondLabel];
}

- (void)creatView {
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, KWidth, KHeight-130-64)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    CGFloat margin = 15;
    CGFloat width = (KWidth-margin*4)/3;
    CGFloat hight = width*80/105;
    
    bgView.frame = CGRectMake(0, 200, KWidth, hight*2+margin*3);
    
    //105/80
    for (int i=0; i<5; i++) {
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(i%3*width+(i%3+1)*margin, i/3*hight+(i/3+1)*margin, width, hight)];
        imgView.userInteractionEnabled = YES;
        imgView.tag = 100+i;
        imgView.image = [UIImage imageNamed:@"上传按钮"];
        [bgView addSubview:imgView];
        
        //添加手势
        UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
        PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
        PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
        [imgView addGestureRecognizer:PrivateLetterTap];
        
        if (i == 0) {
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, hight-20, width, 20)];
            label.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
            label.text = @"默认主图";
            label.textColor = [UIColor whiteColor];
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont systemFontOfSize:14];
            [imgView addSubview:label];
            
        }
    }
    
    
}


//图片点击手势
- (void)tapAvatarView:(UIGestureRecognizer *)reconger {
    
    editView = (UIImageView *)[self.view viewWithTag:reconger.view.tag];
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            // 跳转到相机页面
            UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            //            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            [self.navigationController presentViewController:imagePickerController animated:YES completion:NULL];
        }
        
        
        
    }];
    
    
    UIAlertAction *picAlbumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //跳转到相册
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = NO;
        //        [self presentModalViewController:pickerImage animated:YES];
        [self.navigationController presentViewController:pickerImage animated:YES completion:NULL];
        
        
    }];
    
    UIAlertAction *canceAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertVC addAction:photoAction];
    [alertVC addAction:picAlbumAction];
    [alertVC addAction:canceAction];
    [self presentViewController:alertVC animated:YES completion:NULL];
    
}

#pragma mark -- 成功获得相片还是视频后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
    if ([type isEqualToString:(NSString*)kUTTypeImage]) {
        
        //获取照片的原图
        UIImage *original = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        //将图片大小压缩
        //        UIImage *samllImg = [self scaleImage:original toKb:100];
        
        //        NSData  *imageData2 = UIImageJPEGRepresentation(original,0.5f);
        
        //        UIImage *samllImg = [UIImage imageWithData:imageData2];
        //long length2 = [imageData2 length]/1024.0f;
        // NSLog(@"压缩后大小%ldKB",length2);
        
        UIImage *samllImg = [self compressImage:original newWidth:500];
        NSString *tagStr = [NSString stringWithFormat:@"%ld",editView.tag];
        [self uploadFile:samllImg Withkey:tagStr];
        
        
        
        //        //如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
        //        UIImageWriteToSavedPhotosAlbum(samllImg, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        //
        //        NSURL *picurl=[info objectForKey:UIImagePickerControllerReferenceURL];
    }
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:NULL];
}


- (void)uploadFile:(UIImage *)img Withkey:(NSString *)key{
    
    if (img == nil) {
        return;
    }
    NSData *fileData = UIImageJPEGRepresentation(img, 1.0f);
    NSString *fieleImageStr = [fileData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSDictionary *dataDic = User_listsValue;
    NSString *url = [NSString stringWithFormat:@"%@member/album/upload",Main_Url];
    NSString *number = dataDic[@"number"];
    NSString *token = dataDic[@"token"];
    NSDictionary *dic = @{
                          @"number":number,
                          @"token":token,
                          @"img":fieleImageStr,
                          @"sn":@"",
                          @"name":[NSString stringWithFormat:@"img%@",key]
                          };
    __weak __typeof(self)weakSelf = self;
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    //    __weak typeof(self)WeakSelf = self;
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSDictionary *dataArray = response[@"data"];
            NSString *dicKey = dataArray[@"path"];
            if (dicKey != nil) {
                
                //将图片保存至字典
                [weakSelf.imgData replaceObjectAtIndex:[key integerValue]-100 withObject:dicKey];
                NSLog(@"%@",weakSelf.imgData);
                editView.image = img;
            }
            
        }else {
            
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
        
    }];
    
    
    //    if (self.selecImgBlock != nil) {
    //        self.selecImgBlock(editView.image);
    //    }
    //    [self.navigationController popViewControllerAnimated:YES];
}


- (UIImage *)compressImage:(UIImage *)image newWidth:(CGFloat)newImageWidth
{
    if (!image) return nil;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = newImageWidth;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }
    
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return newImage;
    
}


- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)nextAction {
    
    //sort0
//    default0

    NSDictionary *dataDic = User_listsValue;
    NSString *url = [NSString stringWithFormat:@"%@member/lease/image",Main_Url];
    NSString *number = dataDic[@"number"];
    NSString *token = dataDic[@"token"];
    NSDictionary *dic = @{
                          @"number":number,
                          @"token":token,
                          @"sn":self.sn,
                          @"name0":self.imgData[0],
                          @"sort0":@"0",
                          @"default0":@"1",
                          @"name1":self.imgData[1],
                          @"sort1":@"0",
                          @"default1":@"0",
                          @"name2":self.imgData[2],
                          @"sort2":@"0",
                          @"default2":@"0",
                          @"name3":self.imgData[3],
                          @"sort3":@"0",
                          @"default3":@"0",
                          @"name4":self.imgData[4],
                          @"sort4":@"0",
                          @"default4":@"0",
                          };
    __weak __typeof(self)weakSelf = self;
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    //    __weak typeof(self)WeakSelf = self;
    PublishSuccessViewController *successVc = [[PublishSuccessViewController alloc] init];
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            [weakSelf.navigationController pushViewController:successVc animated:YES];
    
        }else {
            
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
        
    }];

    
}

@end
